/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pk.ecompuefs.micc.dfs.slave;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;

/**
 *
 * @author emanuel
 */
public class SlaveServer extends Thread {

    private static ServerSocket server;
    private static Socket master;
    private Socket client;
    private static String masterIP;
    
    public SlaveServer(Socket socket) {
        this.client = socket;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {

            while (masterIP == null || masterIP.equals("")) {

                masterIP = JOptionPane.showInputDialog("Digite o Endereço do Servidor Master");
                System.out.println(masterIP);

                if (masterIP == null || masterIP.equals("")) {

                    JOptionPane.showMessageDialog(null,
                            "Você não digitou um endereço válido.");
                }

            }

            master = new Socket(masterIP, 4010);
            log("Conectado ao Master Server " + masterIP);
            
            
//======================================================================
            
            server = new ServerSocket(4012);
            log("Slave Server Iniciado na Porta 4012. Aguardando Conexões...");
                    while(true) {
                        
                        Socket socket = server.accept();
                        log("Nova conexão com o cliente " + socket.getInetAddress());
                        Thread ThreadClient = new SlaveServer(socket);
                        ThreadClient.start();
                        
                    }
            
        } catch (UnknownHostException ex) {
            Logger.getLogger(SlaveServer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(SlaveServer.class.getName()).log(Level.SEVERE, null, ex);
        }



    }
    
    /**
     * Recebe as requisições dos clientes
     */

    @Override
    public void run() {
        log("Cliente em execução...");
        while(!client.isClosed()) {
                        
        }
    }
    
      
     /**
     * Exibe informações no console
     * @param msgm 
     */
     private static void log(String msgm) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
        System.out.println(sdf.format(new Date()).toUpperCase() + " => " + msgm);
    }
    
    /**
     * Recebe as requisições do MasterServer
     */
    
    public void serverListening() {
        
        while(!master.isClosed()) {
            
        }
        
    }
}
